package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.WeiboMapper;
import cn.tedu.weibo.vo.MyResult;
import cn.tedu.weibo.vo.User;
import cn.tedu.weibo.vo.Weibo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper mapper;

    @RequestMapping("/weibo/insert")
    public int weiboInsert(Weibo weibo, MultipartFile picFile, HttpSession session) throws IOException {
        //判断是否登录过
        User u = (User) session.getAttribute("u");
        if(u==null){//没有登录
            return 2;
        }
        String fileName = picFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        //文件夹相关
        String dirPath = "D:/upload/";
        File dirFile = new File(dirPath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+fileName;
        //保存文件 异常抛出
        picFile.transferTo(new File(filePath));

        //author,url,created,userId
        weibo.setAuthor(u.getNick());
        weibo.setUrl("/"+fileName);
        weibo.setCreated(new Date());//new Date()得到表示当前系统时间的时间对象
        weibo.setUserId(u.getId());
        //保存到weibo表中
        mapper.insert(weibo);
        return 1;//发布成功
    }

    @RequestMapping("/weibo/select")
    public List<Weibo> select(){
        return mapper.select();
    }

    @RequestMapping("/weibo/select/my")
    public MyResult selectMy(HttpSession session){
        //得到当前登录的用户对象
        User u = (User) session.getAttribute("u");
        if(u==null){//如果没有u 代表未登录返回null 前端接收到的是空字符串
            return new MyResult(2,null);
        }
        //通过当前登录的用户id查询所有微博
        return new MyResult(1,mapper.selectByUserId(u.getId()));
    }

    @RequestMapping("/weibo/delete")
    public void delete(int id){
        mapper.delete(id);
    }

    @RequestMapping("/weibo/select/myDetail")
    public Weibo selectMyDetail(int id){
        return mapper.selectMyDetail(id);
    }

}
